import { defineStore } from "pinia";
import { computed, ref } from "vue";
import { useUserStore } from "./user";
import { insertCartAPI,findNewCartListAPI,deleteCartAPI } from "@/apis/cart";

export const useCartStore = defineStore('cart',()=>{
  const userStore = useUserStore()
  const isLogin = computed(()=>userStore.userInfo.token)
  const cartList = ref([])
  // 获取更新列表
  const getList = async()=>{
    const {data:res} = await findNewCartListAPI()
    cartList.value = res.result
  }
  // 添加
  const addCart = async(goods)=>{
    const { skuId,count } = goods
    if(isLogin.value){
      // 用接口添加
      await insertCartAPI({skuId,count})
      getList()
    }else{
      // 加入本地购物车
      const item = cartList.value.find((item) => goods.skuId === item.skuId )
      if(item){
        item.count = item.count + goods.count
      }else{
        cartList.value.push(goods)
      }
    }
  }

  // 删除
  const deleteCart = async(skuId)=>{
    if(isLogin.value){
      await deleteCartAPI([skuId])
      getList()
    }else{
      // 删除下标值
      const idx = cartList.value.findIndex((item)=> skuId === item.skuId)
      cartList.value.splice(idx,1)
    }
  }

  // 清除
  const clearCart = ()=>{
    cartList.value=[]
  }

  // 计算总数和总额
  const total = computed( ()=> cartList.value.reduce((sum, item) => sum + item.count, 0 ))
  const totalPrice = computed( ()=> cartList.value.reduce((sum, item) => sum + item.count*item.price, 0 ))

  // 单选功能
  const singleCheck = (skuId,selected)=>{
    // find 直接引用，item就是cartList中对应的数据
    const item = cartList.value.find((item)=> skuId === item.skuId )
    item.selected = selected
  }

  // 是否全选
  // every所有元素满足条件返回true
  const isAll = computed(()=>cartList.value.every((item) => item.selected))

  // 全选功能
  const allCheck = (selected)=>{
    cartList.value.forEach((item)=>item.selected = selected)
  }

  // 计算已选中商品数量和价格
  const selectedTotal = computed( ()=> cartList.value.filter(item=> item.selected).reduce((sum, item) => sum + item.count, 0 ) )
  const selectedTotalPrice = computed(()=> cartList.value.filter(item=> item.selected).reduce((sum, item) => sum + item.count*item.price, 0 ))


  return{
    cartList,
    total,
    totalPrice,
    isAll,
    selectedTotal,
    selectedTotalPrice,
    singleCheck,
    addCart,
    deleteCart,
    allCheck,
    clearCart,
    getList
  }
},{
  persist: true,
})
